'use client';

import { FamilyMember } from '../types/family';
import { convertToAncientNumber, convertDateToAncient } from '../types/ancientNumberMap';
import { generateTablePDF } from '../utils/pdfGenerator';

interface TableViewProps {
  familyData: FamilyMember[];
}

const getChildrenCount = (familyData: FamilyMember[], id: string) => {
  const children = familyData.filter(person => person.parentId === id);
  const sonsCount = children.filter(child => child.gender === 'male').length;
  const daughtersCount = children.filter(child => child.gender === 'female').length;
  return { sonsCount, daughtersCount };
};

export default function TableView({ familyData }: TableViewProps) {
  if (familyData.length === 0) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-gray-500 text-lg">暂无族谱数据，请先添加成员</p>
      </div>
    );
  }

  // 家族树节点定义
  interface FamilyTreeNode {
    member: FamilyMember;
    children: FamilyTreeNode[];
  }

  // 将中文排名转换为数字，用于排序
  const getRankingNumber = (ranking: string): number => {
    const rankingMap: { [key: string]: number } = {
      '长子': 1, '长女': 1,
      '次子': 2, '次女': 2,
      '三子': 3, '三女': 3,
      '四子': 4, '四女': 4,
      '五子': 5, '五女': 5,
      '六子': 6, '六女': 6,
      '七子': 7, '七女': 7,
      '八子': 8, '八女': 8,
      '九子': 9, '九女': 9,
      '十子': 10, '十女': 10,
    };
    return rankingMap[ranking] || 999;
  };

  // 子节点排序函数：同generation内男性优先，同性别内按ranking排序
  const sortChildren = (children: FamilyMember[]): FamilyMember[] => {
    return children.sort((a, b) => {
      // 1. 按generation从大到小（generation大的先输出）
      if (a.generation !== b.generation) {
        return b.generation - a.generation;
      }

      // 2. 同generation内，男性优先（左子树）
      if (a.gender !== b.gender) {
        return a.gender === 'male' ? -1 : 1;
      }

      // 3. 同性别内按ranking排序
      return getRankingNumber(a.ranking) - getRankingNumber(b.ranking);
    });
  };

  // 构建家族树
  const buildFamilyTree = (members: FamilyMember[]): FamilyTreeNode[] => {
    // 创建成员映射
    const memberMap = new Map<string, FamilyMember>();
    members.forEach(member => {
      memberMap.set(member.id, member);
    });

    // 找到根节点（没有父节点的成员）
    const roots: FamilyMember[] = members.filter(member =>
      !member.parentId || !memberMap.has(member.parentId)
    );

    // 递归构建树节点
    const buildNode = (member: FamilyMember): FamilyTreeNode => {
      // 找到所有子节点
      const children = members.filter(m => m.parentId === member.id);

      // 对子节点进行排序
      const sortedChildren = sortChildren(children);

      // 递归构建子节点
      const childNodes = sortedChildren.map(child => buildNode(child));

      return {
        member,
        children: childNodes
      };
    };

    // 对根节点进行排序
    const sortedRoots = sortChildren(roots);

    // 构建根节点树
    return sortedRoots.map(root => buildNode(root));
  };

  // 深度优先先序遍历（DLR）
  const preorderTraversal = (nodes: FamilyTreeNode[]): FamilyMember[] => {
    const result: FamilyMember[] = [];

    const traverse = (node: FamilyTreeNode) => {
      // D: 访问当前节点数据
      result.push(node.member);

      // L & R: 遍历所有子节点（按排序后的顺序）
      node.children.forEach(child => traverse(child));
    };

    // 遍历所有根节点
    nodes.forEach(root => traverse(root));

    return result;
  };

  // 构建家族树并进行先序遍历
  const familyTree = buildFamilyTree(familyData);
  const sortedData = preorderTraversal(familyTree).reverse();

  // 找到根祖先的名字（parentId为null的节点）
  const rootAncestor = familyData.find(member => !member.parentId);
  const ancestorName = rootAncestor ? rootAncestor.name : '';

  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    return convertDateToAncient(dateStr);
  };

  // 下载PDF
  const downloadPDF = async () => {
    try {
      await generateTablePDF('tableview-table-container', {
        filename: `${ancestorName}后裔世系名册.pdf`,
        orientation: 'landscape',
        format: 'a3'
      });
    } catch (error) {
      alert('PDF生成失败，请重试');
    }
  };



  // 定义字段信息
  const fields = [
    { key: 'generation', label: '世次', getValue: (person: FamilyMember) => `${convertToAncientNumber(person.generation)}` },
    { key: 'name', label: '姓名', getValue: (person: FamilyMember) => person.name },
    {
      key: 'parent', label: '何人子女', getValue: (person: FamilyMember) => {
        const parent = person.parentId ? familyData.find(p => p.id === person.parentId) : null;
        const name = parent ? parent.name : '';
        const ranking = person.ranking;
        return { parentName: name, ranking: ranking };
      }
    },

    {
      key: 'birthDeathDate',
      label: '生终年月日',
      getValue: (person: FamilyMember) => {
        const birthDate = formatDate(person.birthDate);
        const deathDate = formatDate(person.deathDate);
        return { birth: birthDate, death: deathDate };
      }
    },
    { key: 'biography', label: '履历', getValue: (person: FamilyMember) => person.biography },
    { key: 'spouseName', label: '配偶姓名', getValue: (person: FamilyMember) => person.spouseName },
    {
      key: 'spouseBirthDeathDate',
      label: '生终年月日',
      getValue: (person: FamilyMember) => {
        const spouseBirthDate = formatDate(person.spouseBirthDate);
        const spouseDeathDate = formatDate(person.spouseDeathDate);
        return { birth: spouseBirthDate, death: spouseDeathDate };
      }
    },
    { key: 'spouseBiography', label: '履历', getValue: (person: FamilyMember) => person.spouseBiography },
    {
      key: 'address',
      label: '现在住址',
      getValue: (person: FamilyMember) => {

        return { town: person.town, county: person.county };
      }
    }, {
      key: 'children',
      label: '生子女数',
      getValue: (person: FamilyMember) => {
        const { sonsCount, daughtersCount } = getChildrenCount(familyData, person.id);
        const sonsText = sonsCount > 0 ? `${convertToAncientNumber(sonsCount)}子` : '';
        const daughtersText = daughtersCount > 0 ? `${convertToAncientNumber(daughtersCount)}女` : '';
        return { sons: sonsText, daughters: daughtersText };
      }
    },
    { key: 'notes', label: '备注', getValue: (person: FamilyMember) => person.notes }
  ];

  return (
    <div className="p-6 h-screen flex flex-col">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold text-secondary text-center flex-1">{ancestorName}后裔世系名册</h2>
        <button
          onClick={downloadPDF}
          className="px-4 py-2 text-sm bg-green-500 text-white rounded hover:bg-green-600 transition-colors"
        >
          下载PDF
        </button>
      </div>
      <div className="flex-1 overflow-auto">
        <div className="overflow-x-auto overflow-y-auto h-full">
          <div id="tableview-table-container">
            <table className="border-collapse border border-gray-400 bg-white text-sm w-max">



          <tbody>
            {fields.map((field) => (
              <tr key={field.key}>
                {/* 每个人的该字段值 */}
                {sortedData.map((person) => {
                  const value = field.getValue(person);

                  // 处理合并的日期字段
                  if (field.key === 'birthDeathDate' || field.key === 'spouseBirthDeathDate') {
                    const dateData = value as { birth: string; death: string };
                    const isEmpty = !dateData.birth && !dateData.death;

                    return (
                      <td
                        key={person.id}
                        className={`border border-gray-400 px-3 py-2 text-center text-sm ${isEmpty ? 'bg-gray-50' : 'bg-white'
                          } text-gray-700`}
                        style={{
                          writingMode: 'vertical-rl', textOrientation: 'upright'
                        }}
                      >
                        {isEmpty ? '' : (
                          <div className="flex flex-col items-start space-y-1">
                            <div className="text-xs whitespace-nowrap" title={dateData.birth}>
                              生 {dateData.birth}
                            </div>
                            {/* <div className="text-xs text-gray-400 text-center">—</div> */}
                            <div className="text-xs whitespace-nowrap px-3" title={dateData.death}>
                              终 {dateData.death}
                            </div>
                          </div>
                        )}
                      </td>
                    );
                  }
                  //地址合并处理
                  if (field.key === 'address') {
                    const address = value as { town: string; county: string };
                    const isEmpty = !address.town && !address.county;

                    return (
                      <td
                        key={person.id}
                        className={`border border-gray-400 px-3 py-2 text-center text-sm ${isEmpty ? 'bg-gray-50' : 'bg-white'
                          } text-gray-700`}
                        style={{
                          writingMode: 'vertical-rl', textOrientation: 'upright'
                        }}
                      >
                        {isEmpty ? '' : (
                          <div className="flex flex-col  space-y-1">
                            <div className="text-sm whitespace-nowrap" title={address.town}>
                              {address.town}
                            </div>
                            <div className="text-sm whitespace-nowrap " title={address.county}>
                              {address.county}
                            </div>
                          </div>
                        )}
                      </td>
                    );
                  }
                  //何人子女
                  if (field.key === 'parent') {
                    const nameRanking = value as { parentName: string; ranking: string };
                    const isEmpty = !nameRanking.parentName && !nameRanking.ranking;

                    return (
                      <td
                        key={person.id}
                        className={`border border-gray-400 px-3 py-2 text-center text-sm ${isEmpty ? 'bg-gray-50' : 'bg-white'
                          } text-gray-700`}
                        style={{
                          writingMode: 'vertical-rl', textOrientation: 'upright'
                        }}
                      >
                        {isEmpty ? '' : (
                          <div className="flex flex-col  space-y-1">
                            <div className="text-sm whitespace-nowrap" title={nameRanking.parentName}>
                              {nameRanking.parentName}
                            </div>
                            <div className="text-sm whitespace-nowrap " title={nameRanking.ranking}>
                              {nameRanking.ranking}
                            </div>
                          </div>
                        )}
                      </td>
                    );
                  }

                  //生子女数
                  if (field.key === 'children') {

                    const childrens = value as { sons: string; daughters: string };
                    const isEmpty = !childrens.sons && !childrens.daughters;

                    return (
                      <td
                        key={person.id}
                        className={`border border-gray-400 px-3 py-2 text-center text-sm ${isEmpty ? 'bg-gray-50' : 'bg-white'
                          } text-gray-700`}
                        style={{
                          writingMode: 'vertical-rl', textOrientation: 'upright'
                        }}
                      >
                        {isEmpty ? '' : (
                          <div className="flex flex-col  space-y-1">
                            <div className="text-sm whitespace-nowrap" title={childrens.sons}>
                              {childrens.sons}
                            </div>
                            <div className="text-sm whitespace-nowrap " title={childrens.daughters}>
                              {childrens.daughters}
                            </div>
                          </div>
                        )}
                      </td>
                    );
                  }


                  // 处理普通字段
                  const isEmpty = !value || (typeof value === 'string' && value.trim() === '');

                  return (
                    <td
                      key={person.id}
                      className={`border border-gray-400 px-6 py-2 text-center text-lg ${isEmpty ? 'bg-gray-50' : 'bg-white'
                        } ${field.key === 'name'
                          ? (person.gender || 'male') === 'male' ? 'text-blue-600 font-bold' : 'text-pink-600 font-bold'
                          : field.key === 'spouseName' && value
                            ? (person.gender || 'male') === 'male' ? 'text-pink-600 font-bold' : 'text-blue-600 font-bold'
                            : 'text-gray-700'
                        }`}
                      style={{
                        writingMode: 'vertical-rl', textOrientation: 'upright'
                      }}
                    >
                      {isEmpty ? '' : (
                        <div className="truncate" title={typeof value === 'string' ? value : ''}>
                          {typeof value === 'string' ? value : ''}
                        </div>
                      )}
                    </td>
                  );
                })}
                {/* 字段名称 */}
                <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium text-center " style={{ writingMode: 'vertical-rl', textOrientation: 'upright' }}>
                  {field.key === 'spouseName' ? (
                    <div className="flex flex-row justify-center space-x-1">
                      <div className="flex flex-col">
                        <span>配</span>
                        <span>偶</span>
                      </div>
                      <div className="flex flex-col">
                        <span>姓</span>
                        <span>名</span>
                      </div>
                    </div>
                  ) : field.key === 'address' ? (
                    <div className="flex flex-row justify-center space-x-1">
                      <div className="flex flex-col">
                        <span>现</span>
                        <span>住</span>
                      </div>
                      <div className="flex flex-col">
                        <span>在</span>
                        <span>址</span>
                      </div>
                    </div>
                  ) : field.key === 'children' ? (
                    <div className="flex flex-row justify-center space-x-1">
                      <div className="flex flex-col">
                        <span>生</span>
                        <span>女</span>
                      </div>
                      <div className="flex flex-col">
                        <span>子</span>
                        <span>数</span>
                      </div>
                    </div>
                  ) : (
                    field.label
                  )}
                </td>
              </tr>
            ))}
          </tbody>
          </table>
          </div>
        </div>
      </div>
    </div>
  );
}